const app = getApp();
const userInfo = wx.getStorageSync('userinfo');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    towerUrl: app.globalData.towerUrl,
    fileUrl: app.globalData.fileUrl,
    task: {},
    staffList: [],
    fixImgList: [],
    afterPic: '',
    taskId: '',
    dealFlag: '',
    flowType: '',
    flowId: '',
    flowDept: '',
    bigSearchShow: false,
    bigSearchType: "",
    searchDataList: []
  },

  getStaffByDept: function (dutyDept) {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/staffInfo/wx/getStaffByDept?dept=' + dutyDept,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取部门员工信息:', res.data);
        var data = res.data;
        that.setData({
          staffList: data.data,
        })
      }
    });
  },

  searchSelect(e) {
    const params = {}
    params['corrector'] = e.detail.name

    this.setData({
      ...params
    })
  },

  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.fixImgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            fixImgList: this.data.fixImgList
          })
        }
      }
    })
  },
  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      success(res) { // 将图片上传到服务器
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.fixImgList.length != 0) {
              that.setData({
                fixImgList: that.data.fixImgList.concat(tempArray)
              })
            } else {
              that.setData({
                fixImgList: tempArray
              })
            }
          }
        })
      }
    })
  },
  getTaskInfo: function (taskId) {
    var that = this;
    wx.request({
      url: that.data.towerUrl + '/moaTask/wx/' + taskId,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'userNo': wx.getStorageSync('userinfo').siocSapNo // 请求头 
      },
      success(res) {
        console.log('获取任务详情:', res.data);
        var data = res.data;

        that.setData({
          task: data.data
        });
        if (0 == that.data.flowType) {
          that.getStaffByDept(that.data.flowDept);
        }
      }
    });
  },

  submitForm(e) {
    var that = this;
    const formData = e.detail.value;
    formData.taskId = that.data.taskId;
    formData.flowId = that.data.flowId;
    formData.flowDept = that.data.flowDept;
    formData.taskCode = that.data.task.taskCode;
    var errMsg = "";
    var endPoint = "";
    //指派整改人
    if (that.data.flowType == 0) {
      formData.corrector = that.data.corrector;
      if (!formData.corrector) {
        errMsg = errMsg + "任务责任人不能为空;";
      }
      endPoint = "/moaTask/wx/assign";
    }
    //整改完成
    if (that.data.flowType == 1) {
      formData.fixImgList = that.data.fixImgList;
      if (formData.fixImgList.length < 1 && !formData.explanation) {
        errMsg = errMsg + "完成情况说明及图片不能都为空;";
      }
      endPoint = "/moaTask/wx/fixDone";
    }
    console.log('form发生了submit事件，携带数据为：', formData);
    if (errMsg.length > 0) {
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }
    // 向服务器提交表单数据
    wx.request({
      url: that.data.towerUrl + endPoint,
      method: 'POST',
      data: formData,
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/moa-task-list/moa-task-list?dealFlag=2'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  pass() {
    var that = this;
    wx.request({
      url: that.data.towerUrl + '/moaTask/wx/pass',
      method: 'POST',
      data: {
        'taskId': that.data.taskId,
        'flowId': that.data.flowId
      },
      success: function (res) {
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/moa-task-list/moa-task-list?dealFlag=2'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  refuse() {
    var that = this;
    wx.showModal({
      editable: true, //显示输入框
      placeholderText: '输入退回原因', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          wx.request({
            url: that.data.towerUrl + '/moaTask/wx/refuse',
            method: 'POST',
            data: {
              'taskId': that.data.taskId,
              'flowId': that.data.flowId,
              'remark': res.content,
              'flowDept': that.data.flowDept,
              'taskCode': that.data.task.taskCode
            },
            success: function (res) {
              console.log('表单提交成功', res);
              if (200 == res.data.code) {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      wx.reLaunch({
                        url: '/pages/moa-task-list/moa-task-list?dealFlag=2'
                      })
                    }
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none'
                });
              }
            },
            fail: function (err) {
              console.error('表单提交失败', err);
              wx.showToast({
                title: '表单提交失败',
                icon: 'none'
              });
            }
          });
        } else {
          console.log('用户点击了取消')
        }
      }
    })
  },
  ViewImage2(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    console.log(current);
    for (let key in this.data.fixImgList) {
      urls.push(this.data.fileUrl + this.data.fixImgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  goTaskFlow() {
    var that = this;
    wx.navigateTo({
      url: '/pages/moa-task-flow/moa-task-flow?taskId=' + that.data.taskId,
    })
  },
  doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      staff: () => {
        if (this.data.staffList.length == 0) {
          wx.showToast({
            title: '暂无整改人指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.staffList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      },

      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options);
    this.setData({
      taskId: options.taskId,
      dealFlag: options.dealFlag,
      flowType: options.flowType,
      flowId: options.flowId,
      flowDept: options.flowDept,
      remark: options.remark,
      fixImgList: options.afterPic != 'null' ? options.afterPic.split(',') : []
    });
    this.getTaskInfo(options.taskId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})